package com.tool.app.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpClient {

	public static <T> T postJson(String url, Object data, Class<T> cls) {
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		requestFactory.setReadTimeout(5000); // 设置读取超时（毫秒）
		requestFactory.setConnectTimeout(5000); // 设置连接超时（毫秒）
		RestTemplate restTemplate = new RestTemplate(requestFactory);
		//restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(data, null), byte[].class).getBody();
		restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		String value;
		if (data instanceof String) {
			value = (String) data;
		} else {
			value = JSON.toJSONString(data);
		}
		HttpEntity<String> requestEntity = new HttpEntity<>(value, headers);
		ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, requestEntity, cls);
		return responseEntity.getBody();
	}

	/**
	 * 非对象返回结果异常判断
	 * @param args
	 */
	public static void main(String[] args) {
		byte[] bytes = HttpClient.postJson("www.baidu.com", new HashMap<>(), byte[].class);
		Map<String,Object> result = JSON.parseObject(bytes, Map.class);
		if (ObjectUtils.isEmpty(result)) {
			BASE64Encoder encoder = new BASE64Encoder();
			String encode = encoder.encode(bytes);
			String data = encode.replaceAll("\r\n", "");
			String baseStr = String.format("data:image/jpg;base64,%s", data);
			System.out.println(baseStr);
		}
	}
}